package com.quanquan.store.repository.marketActivity.turnTable;

import com.quanquan.store.entity.marketActivity.turnTable.TurnTableGift;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @ClassName TurnTableGiftRepository
 * @Description
 * @Author Owen
 * @Date 2019/9/19 0019 上午 10:36
 * @Version V1.0
 **/
public interface TurnTableGiftRepository extends JpaRepository<TurnTableGift,Long>, JpaSpecificationExecutor<TurnTableGift> {

    List<TurnTableGift> findAllByActivityIdAndActivityTypeAndStatusAndStartTimeBeforeAndEndTimeAfterOrderByGiftIndexAsc(Long activityId, Integer activityType, Integer status, Date startTime, Date endTime);

    List<TurnTableGift> findAllByActivityIdAndStatusAndStartTimeBeforeAndEndTimeAfterAndRemainTotalGreaterThan(Long activityId, Integer status, Date startTime, Date endTime, int remianTotal);

    TurnTableGift findFirstByActivityIdAndStatusAndStartTimeBeforeAndEndTimeAfterAndGiftType(Long activityId, Integer status, Date startTime, Date endTime, int giftType);

    @Query(value = "select sum(odds) from oo_turn_table_gift where activity_id=?1 and status=1 and remain_total > 0 and start_time <= now() and end_time > now() ",nativeQuery = true)
    Integer findSumOdds(Long scratchCardId);

    @Transactional
    @Modifying
    @Query(value = "update oo_turn_table_gift set remain_total = remain_total - 1 where id = ?1 and remain_total > 0",nativeQuery = true)
    Integer substractStock(Long giftId);
}
